import _ from "lodash";
import { message } from "antd";
import { WeaTools, WeaLocaleProvider } from 'ecCom';
import { API_URL } from "../constants";

const { getLabel } = WeaLocaleProvider;
const { success, error } = message;
const { callApi } = WeaTools;

export default {
  api: modName => {
    return (action, settings = {}) => { // 封装callApi
      let {
        data = '',
        msg = '',
        type = 'get',
        dataType = 'json',
        ignoreError = false,
        url = `${API_URL}${modName}/${action}`
      } = settings;
      return new Promise((resolve, reject) => {
        callApi(url, type, data, dataType).then(res => {
          if (res.api_status || res.status) {
            
            msg && success(msg);
            return resolve(res.data);
          }

          let errmsg = res.api_errormsg || getLabel(383311, "服务器处理请求时出现异常");

          errmsg = !ignoreError && errmsg.replace("catch exception :", "").trim();

          errmsg && error(errmsg)

          return reject(res);
        });
      });
    };
  },
  UUID: (len = 32) => {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (Math.random() * 16) | 0;
      const v = c === 'x' ? r : ((r & 0x3) | 0x8);

      return v.toString(16);
    }).substring(0, len);
  },
  isUrl: str => /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig.test(str),
  arrayMove: (array, from, to) => {
    array = array.slice();
    array.splice((to < 0 ? array.length + to : to), 0, array.splice(from, 1)[0]);
    return array;
  },
  sort: (items, changes) => {
    const { oldIndex, newIndex } = changes;

    if(oldIndex === newIndex) return items;

    const item = items[oldIndex];
    const newItems = items.filter((v, index) => index !== oldIndex);

    newItems.splice(newIndex, 0, item);

    return newItems;
  },
  addItem: (items, newItem, newIndex) => {
    const newItems = [...items];

    newItems.splice(newIndex, 0, newItem);

    return newItems;
  },
  isEqual: (o1, o2) => {
    return JSON.stringify(o1) === JSON.stringify(o2);
  },
  toPixel: pixel => {
    pixel = String(pixel);

    if (~pixel.indexOf('px')) return pixel;

    return `${pixel}px`;
  },
  reduce: numberArr => {
    if (!_.isArrayLike(numberArr) || !numberArr.length) return 0;
    
    return numberArr.reduce((prev, current) => prev + current);
  },
  copyIndex: (arr, index, map = v => v) => {
    arr.splice(index + 1, 0, map(arr[index]));
  },
  throttle: function (callback, time, count) {
    let index = 0;
    let timer;
    const self = this;
    
    return function () { 
      timer = setInterval(() => {
        count === index && clearInterval(timer);

        let flag = callback.call(self);

        flag && clearInterval(timer);
        index++;
      }, time);
    }

  },
  scrollSmoothTo: function (position) {
    if (!window.requestAnimationFrame) {
      window.requestAnimationFrame = function (callback, element) {
        return setTimeout(callback, 17);
      };
    }
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    let step = function () {
      // 距离目标滚动距离
      let distance = position - scrollTop;
      // 目标滚动位置
      scrollTop = scrollTop + distance / 5;
      if (Math.abs(distance) < 1) {
        window.scrollTo(0, position);
      } else {
        window.scrollTo(0, scrollTop);
        requestAnimationFrame(step);
      }
    };
    step();
  },
  toUpperCase: function (str, indent = 1) {
    if (indent === void 0) return str.toUpperCase();
    
    return str.replace(/[a-z]/, m => m.toUpperCase());
  },
  // 获取触发事件元素冒泡过程中的所有元素
  getComposed: event => {
    const e = event || window.event;

    if (!e) return [];

    if (e.composedPath) return e.composedPath();

    return e.path;
  }
};